package com.example.bingobox.ui.todobox;

import android.app.DatePickerDialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.bingobox.R;
import com.example.bingobox.databinding.FragmentTodoboxBinding;
import com.example.bingobox.model.TodoBox;
import com.example.bingobox.model.Task;
import com.example.bingobox.model.Label;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import android.widget.TimePicker;
import android.widget.Spinner;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import com.example.bingobox.adapter.TimeLabelAdapter;
import com.example.bingobox.adapter.TimeSpanSelectionAdapter;
import com.example.bingobox.adapter.TimeSpanAdapter;
import androidx.annotation.Nullable;
import androidx.navigation.Navigation;
import com.example.bingobox.view.NetworkSelector;
import android.widget.LinearLayout;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import android.app.Dialog;
import android.view.Window;
import android.view.WindowManager;
import android.view.Gravity;
import android.widget.DatePicker;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.example.bingobox.ui.todobox.SceneSelectionAdapter;
import java.util.stream.Collectors;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.text.ParseException;
import java.nio.file.Files;
import com.example.bingobox.view.ClockTimeSelector;
import com.example.bingobox.adapter.SceneGroupDisplayAdapter;
import com.example.bingobox.adapter.TodoBoxAdapter;
import android.app.TimePickerDialog;
import com.example.bingobox.model.TodoBoxData;
import java.lang.reflect.Type;
import com.example.bingobox.adapter.TaskSelectionAdapter;
import android.text.Editable;
import android.text.TextWatcher;
import com.example.bingobox.adapter.SearchTodoBoxAdapter;

public class TodoBoxFragment extends Fragment {
    private FragmentTodoboxBinding binding;
    private TodoBoxAdapter adapter;
    private SearchTodoBoxAdapter searchResultsAdapter;
    private List<TodoBox> todoBoxes;
    private Map<String, Task> taskMap;
    private final Gson gson = new Gson();
    private List<Label> labels = new ArrayList<>();
    private TimeSpanAdapter timeSpanAdapter;
    private ChipGroup scenesChipGroup;
    private Set<String> scenes = new LinkedHashSet<>();
    private Chip wifiChip;
    private Chip mobileChip;
    private Chip noNetworkChip;
    private ChipGroup locationChipGroup;
    private SceneGroupAdapter sceneAdapter;
    private Set<String> currentScenes = new LinkedHashSet<>();
    private RecyclerView scenesRecyclerView;
    private SceneGroupDisplayAdapter sceneGroupDisplayAdapter;
    private Set<String> currentDrawnTaskIds = new HashSet<>();  // 当前会话中已抽取的任务ID

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentTodoboxBinding.inflate(inflater, container, false);
        View view = binding.getRoot();

        // 设置搜索功能
        binding.searchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                String query = s.toString().toLowerCase().trim();
                filterTodoBoxes(query);
            }
        });

        // 设置搜索结果列表
        RecyclerView searchResultsRecyclerView = binding.searchResultsRecyclerView;
        searchResultsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        searchResultsAdapter = new SearchTodoBoxAdapter(  // 使用新的适配器
            getContext(),
            new ArrayList<>(),
            new SearchTodoBoxAdapter.OnTodoBoxActionListener() {
                @Override
                public void onEditClick(TodoBox todoBox) {
                    showEditTodoBoxDialog(todoBox);
                }

                @Override
                public void onDeleteClick(TodoBox todoBox) {
                    new MaterialAlertDialogBuilder(requireContext())
                        .setTitle("删除任务盒")
                        .setMessage("确定要删除这个任务盒吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            todoBoxes.remove(todoBox);
                            saveData();
                            filterTodoBoxesByScene();
                        })
                        .setNegativeButton("取消", null)
                        .show();
                }
            }
        );
        searchResultsRecyclerView.setAdapter(searchResultsAdapter);

        // 初始化场景相关按钮
        Button manageSceneButton = view.findViewById(R.id.btn_scene_manage);
        manageSceneButton.setOnClickListener(v -> showManageSceneDialog());

        Button newSceneButton = view.findViewById(R.id.btn_add_scene);
        newSceneButton.setOnClickListener(v -> showNewSceneDialog());

        // 初始化网络类型相关的 Chip
        wifiChip = view.findViewById(R.id.chip_wifi);
        mobileChip = view.findViewById(R.id.chip_mobile);
        noNetworkChip = view.findViewById(R.id.chip_no_network);
        locationChipGroup = view.findViewById(R.id.chip_group_locations);

        // 初始化数据结构
        todoBoxes = new ArrayList<>();
        taskMap = new HashMap<>();
        currentDrawnTaskIds.clear();  // 清空当前会话的已抽取任务列表

        // 加载数据
        loadData();
        // 进行场景筛选
        filterTodoBoxesByScene();

        // 设置RecyclerView和适配器
        binding.recyclerTodobox.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new TodoBoxAdapter(
                getContext(),
                todoBoxes,
                taskMap,
                labels,
                this::saveData,
                new TodoBoxAdapter.OnTodoBoxActionListener() {
                    @Override
                    public void onExpandClick(TodoBox todoBox) {
                        todoBox.setExpanded(!todoBox.isExpanded());
                        adapter.notifyItemChanged(todoBoxes.indexOf(todoBox));
                    }

                    @Override
                    public void onEditClick(TodoBox todoBox) {
                        showEditTodoBoxDialog(todoBox);
                    }

                    @Override
                    public void onDeleteClick(TodoBox todoBox) {
                        new MaterialAlertDialogBuilder(requireContext())
                            .setTitle("删除任务盒")
                            .setMessage("确定要删除这个任务盒吗？")
                            .setPositiveButton("确定", (dialog, which) -> {
                                todoBoxes.remove(todoBox);
                                saveData();
                                filterTodoBoxesByScene();
                            })
                            .setNegativeButton("取消", null)
                            .show();
                    }

                    @Override
                    public void onDrawTask(TodoBox todoBox, Task task) {
                        // 获取该任务盒中未被抽取的任务
                        List<Task> availableTasks = new ArrayList<>();
                        if (todoBox.getListData() != null && todoBox.getListData().getList() != null) {
                            for (TodoBox.TaskRef taskRef : todoBox.getListData().getList()) {
                                Task fullTask = taskMap.get(taskRef.getTaskId());
                                if (fullTask != null && 
                                    !currentDrawnTaskIds.contains(taskRef.getTaskId()) && 
                                    isTaskTimeValid(fullTask)) {
                                    availableTasks.add(fullTask);
                                }
                            }
                        }

                        if (availableTasks.isEmpty()) {
                            Toast.makeText(getContext(), "当前没有可抽取的任务", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        // 随机抽取一个任务
                        Task selectedTask = availableTasks.get(new Random().nextInt(availableTasks.size()));
                        currentDrawnTaskIds.add(selectedTask.getId());

                        // 构建任务详细信息
                        StringBuilder message = new StringBuilder();
                        message.append("任务名称：").append(selectedTask.getName()).append("\n\n");
                        
                        if (selectedTask.getDescription() != null && !selectedTask.getDescription().isEmpty()) {
                            message.append("描述：").append(selectedTask.getDescription()).append("\n\n");
                        }
                        
                        message.append("截止时间：").append(formatDate(selectedTask.getDeadline()));

                        // 显示抽取到的任务
                        new MaterialAlertDialogBuilder(requireContext())
                            .setTitle("抽取到的任务")
                            .setMessage(message.toString())
                            .setPositiveButton("确定", null)
                            .setNegativeButton("重新抽取", (dialog, which) -> {
                                // 重新抽取任务
                                onDrawTask(todoBox, selectedTask);
                            })
                            .show();
                    }

                    @Override
                    public void onEditTask(TodoBox todoBox, Task task) {
                        showEditTaskDialog(task);
                    }

                    @Override
                    public void onDeleteTask(TodoBox todoBox, Task task) {
                        new MaterialAlertDialogBuilder(requireContext())
                            .setTitle("删除任务")
                            .setMessage("确定要从任务盒中删除任务 \"" + task.getName() + "\" 吗？")
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 从任务盒中移除任务引用
                                if (todoBox.getListData() != null && todoBox.getListData().getList() != null) {
                                    todoBox.getListData().getList().removeIf(ref -> 
                                        ref.getTaskId().equals(task.getId()));
                                }
                                // 从当前会话的已抽取列表中移除
                                currentDrawnTaskIds.remove(task.getId());
                                // 保存更改
                                saveData();
                                // 刷新界面
                                adapter.notifyDataSetChanged();
                            })
                            .setNegativeButton("取消", null)
                            .show();
                    }
                }
        );
        binding.recyclerTodobox.setAdapter(adapter);

        // 设置添加按钮点击事件
        binding.btnAddTodobox.setOnClickListener(v -> showAddTodoBoxDialog());

        // 初始化场景选择器
        scenesRecyclerView = view.findViewById(R.id.recycler_scenes);
        if (scenesRecyclerView != null) {
            scenesRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
            sceneGroupDisplayAdapter = new SceneGroupDisplayAdapter(
                    (scene, isSelected) -> {
                        if (isSelected) {
                            currentScenes.add(scene);  // scene 已经是完整的场景名（如 "出行-飞机"）
                        } else {
                            currentScenes.remove(scene);
                        }
                        saveData();
                        // 更新任务盒的可见性
                        filterTodoBoxesByScene();
                    },
                    currentScenes  // 使用 currentScenes 而不是新建的 Set
            );
            scenesRecyclerView.setAdapter(sceneGroupDisplayAdapter);
            sceneGroupDisplayAdapter.setScenes(scenes);
        }

        // 初始化更新时间按钮
        Button updateTimeButton = view.findViewById(R.id.btn_update_time);
        updateTimeButton.setOnClickListener(v -> {
            updateTimeVisibility();
        });

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void loadData() {
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");
            
            if (todoboxFile.exists()) {
                try (FileReader reader = new FileReader(todoboxFile)) {
                    TodoBoxData data = gson.fromJson(reader, TodoBoxData.class);
                    
                    // 更新任务映射
                    taskMap.clear();
                    if (data.getTasks() != null) {
                        for (Task task : data.getTasks()) {
                            taskMap.put(task.getId(), task);
                        }
                    }
                    
                    // 更新任务盒列表
                    todoBoxes.clear();
                    if (data.getTodoBoxes() != null) {
                        todoBoxes.addAll(data.getTodoBoxes());
                    }
                    
                    // 更新场景集合
                    scenes.clear();
                    if (data.getScenes() != null) {
                        scenes.addAll(data.getScenes());
                    }
                    
                    // 更新当前场景
                    currentScenes.clear();
                    if (data.getCurrentScene() != null) {
                        currentScenes.addAll(data.getCurrentScene());
                    }
                    
                    // 更新标签列表
                    labels.clear();
                    if (data.getLabels() != null) {
                        labels.addAll(data.getLabels());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "加载数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void saveData() {
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            if (!dataDir.exists()) {
                dataDir.mkdirs();
            }
            
            File todoboxFile = new File(dataDir, "todobox.json");
            
            // 使用 TodoBoxData 类来保存数据
            TodoBoxData data = new TodoBoxData();
            data.setTasks(new ArrayList<>(taskMap.values()));
            data.setTodoBoxes(new ArrayList<>(todoBoxes));
            data.setScenes(new ArrayList<>(scenes));
            data.setCurrentScene(new ArrayList<>(currentScenes));
            data.setLabels(new ArrayList<>(labels));
            
            try (FileWriter writer = new FileWriter(todoboxFile)) {
                writer.write(gson.toJson(data));
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "保存数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // 添加场景排序方法
    private List<String> getSortedScenes() {
        Map<String, List<String>> sceneGroups = new LinkedHashMap<>();

        // 按大场景分组
        for (String scene : scenes) {
            String[] parts = scene.split("-");
            if (parts.length == 2) {
                String majorScene = parts[0];
                sceneGroups.computeIfAbsent(majorScene, k -> new ArrayList<>()).add(scene);
            }
        }

        // 合并所有场景，保持相同大场景的场景排在一起
        List<String> sortedScenes = new ArrayList<>();
        for (List<String> group : sceneGroups.values()) {
            sortedScenes.addAll(group);
        }

        return sortedScenes;
    }

    // 修改场景更新方法
    private void updateSceneDisplay() {
        if (sceneGroupDisplayAdapter != null) {
            sceneGroupDisplayAdapter.setScenes(scenes);
        }
    }

    // 根据场景筛选任务盒
    private void filterTodoBoxesByScene() {
        try {
            List<TodoBox> filteredBoxes = new ArrayList<>();
            
            for (TodoBox todoBox : todoBoxes) {
                // 首先检查可见性
                if (!todoBox.isVisible()) {
                    continue;  // 如果不可见，直接跳过
                }
                
                // 然后检查场景
                if (currentScenes.isEmpty()) {
                    // 如果没有选中的场景，显示所有可见的任务盒
                    filteredBoxes.add(todoBox);
                } else {
                    // 如果有选中的场景，检查是否包含任何一个选中的场景
                    for (String selectedScene : currentScenes) {
                        if (todoBox.getScenes() != null && todoBox.getScenes().contains(selectedScene)) {
                            filteredBoxes.add(todoBox);
                            break;
                        }
                    }
                }
            }

            // 更新适配器显示
            if (adapter != null) {
                adapter.updateTodoBoxes(filteredBoxes);
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "筛选失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isTimeInRange(Task.TimeLabel timeLabel, int currentHour, int currentMinute) {
        int startHour = timeLabel.getStartHour();
        int startMinute = timeLabel.getStartMinute();
        int endHour = timeLabel.getEndHour();
        int endMinute = timeLabel.getEndMinute();

        // 将时间转换为分钟数以便比较
        int currentTime = currentHour * 60 + currentMinute;
        int startTime = startHour * 60 + startMinute;
        int endTime = endHour * 60 + endMinute;

        // 特殊处理跨天的情况（结束时间小于开始时间）
        if (endTime < startTime) {
            // 如果结束时间在凌晨（比如01:00），说明跨天了
            // 此时需要特殊处理时间比较
            return currentTime >= startTime || currentTime <= endTime;
        } else {
            // 普通情况：开始时间小于结束时间
            return currentTime >= startTime && currentTime <= endTime;
        }
    }

    private void updateTimeVisibility() {
        Calendar now = Calendar.getInstance();
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int minute = now.get(Calendar.MINUTE);
        int dayOfWeek = now.get(Calendar.DAY_OF_WEEK);
        
        // 获取当前星期对应的日期类型
        String currentDay = getDayOfWeek(dayOfWeek);
        String dayType = getDayType(currentDay);
        
        // 如果获取不到日期类型，将所有任务盒设为不可见
        if (dayType == null) {
            for (TodoBox todoBox : todoBoxes) {
                todoBox.setVisible(false);
            }
            saveData();
            adapter.notifyDataSetChanged();
            return;
        }
        
        // 当前时间（以分钟为单位）
        int currentTime = hour * 60 + minute;
        
        // 更新每个任务盒的可见性
        boolean anyChanges = false;
        
        for (TodoBox todoBox : todoBoxes) {
            boolean isVisible = false;
            
            // 如果任务盒没有时间标签，则始终可见
            if (todoBox.getTimeLabels() == null || todoBox.getTimeLabels().isEmpty()) {
                isVisible = true;
            } else {
                // 检查每个时间标签
                for (Task.TimeLabel timeLabel : todoBox.getTimeLabels()) {
                    if (timeLabel.getDayType().equals(dayType)) {
                        if (timeLabel.isAllDay()) {
                            isVisible = true;
                            break;
                        }
                        
                        // 获取开始和结束时间
                        int startTime = timeLabel.getStartHour() * 60 + timeLabel.getStartMinute();
                        int endTime = timeLabel.getEndHour() * 60 + timeLabel.getEndMinute();
                        
                        // 检查时间是否在范围内
                        if (endTime < startTime) {  // 跨天的情况
                            if (currentTime >= startTime || currentTime <= endTime) {
                                isVisible = true;
                                break;
                            }
                        } else {  // 不跨天的情况
                            if (currentTime >= startTime && currentTime <= endTime) {
                                isVisible = true;
                                break;
                            }
                        }
                    }
                }
            }
            
            // 如果可见性发生变化，记录下来
            if (todoBox.isVisible() != isVisible) {
                anyChanges = true;
                todoBox.setVisible(isVisible);
            }
        }
        
        // 如果有任何改变，保存数据并更新界面
        if (anyChanges) {
            saveData();
        }
        
        // 无论是否有改变，都刷新界面显示
        adapter.updateTodoBoxes(todoBoxes);  // 更新适配器中的任务盒列表
        filterTodoBoxesByScene();  // 根据当前场景和可见性过滤任务盒
        adapter.notifyDataSetChanged();
    }

    // 获取星期几的字符串
    private String getDayOfWeek(int dayOfWeek) {
        switch (dayOfWeek) {
            case Calendar.MONDAY: return "monday";
            case Calendar.TUESDAY: return "tuesday";
            case Calendar.WEDNESDAY: return "wednesday";
            case Calendar.THURSDAY: return "thursday";
            case Calendar.FRIDAY: return "friday";
            case Calendar.SATURDAY: return "saturday";
            case Calendar.SUNDAY: return "sunday";
            default: return "monday";
        }
    }

    // 获取日期类型
    private String getDayType(String day) {
        for (Label label : labels) {
            if (label.getStandard().equals("week") && label.getCoupleData() != null) {
                return label.getCoupleData().getCouple().get(day);
            }
        }
        return null;
    }

    private void showManageSceneDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_scene, null);
        RecyclerView scenesList = dialogView.findViewById(R.id.list_scenes);
        scenesList.setLayoutManager(new LinearLayoutManager(requireContext()));

        // 使用排序后的场景列表
        List<String> sortedScenes = getSortedScenes();
        sceneAdapter = new SceneGroupAdapter(new SceneGroupAdapter.OnSceneActionListener() {
            @Override
            public void onMajorSceneClick(String majorScene) {
                showAddMinorSceneDialog(majorScene);
            }

            @Override
            public void onSceneDelete(String scene) {
                new MaterialAlertDialogBuilder(requireContext())
                        .setTitle("删除场景")
                        .setMessage("确定要删除场景\"" + scene + "\"吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            scenes.remove(scene);
                            // 从所有任务盒中移除该场景
                            for (TodoBox box : todoBoxes) {
                                Set<String> boxScenes = box.getScenes();
                                if (boxScenes != null) {
                                    boxScenes.remove(scene);
                                }
                            }
                            updateSceneDisplay();
                            sceneAdapter.setScenes(getSortedScenes());  // 使用成员变量
                            saveData();
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
        sceneAdapter.setScenes(sortedScenes);
        scenesList.setAdapter(sceneAdapter);

        new MaterialAlertDialogBuilder(requireContext())
                .setView(dialogView)
                .setPositiveButton("关闭", null)
                .show();
    }

    private void showAddMinorSceneDialog(String majorScene) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_minor_scene, null);
        EditText minorSceneInput = dialogView.findViewById(R.id.edit_minor_scene);

        new MaterialAlertDialogBuilder(requireContext())
                .setTitle("添加小场景")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    String minorScene = minorSceneInput.getText().toString().trim();

                    if (!isValidSceneName(minorScene)) {
                        Toast.makeText(requireContext(), "场景中有非法字符", Toast.LENGTH_SHORT).show();
                        minorSceneInput.setText("");
                        return;
                    }

                    // 构建新场景
                    String newScene = majorScene + "-" + minorScene;

                    // 将新场景添加到集合的对应位置
                    List<String> sortedScenes = getSortedScenes();
                    int insertIndex = 0;
                    for (int i = 0; i < sortedScenes.size(); i++) {
                        String scene = sortedScenes.get(i);
                        if (scene.startsWith(majorScene + "-")) {
                            insertIndex = i + 1;
                        }
                    }

                    // 更新场景集合
                    scenes.add(newScene);
                    updateSceneDisplay();
                    saveData();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private boolean isValidSceneName(String name) {
        return name != null && !name.isEmpty() && name.matches("^[a-zA-Z0-9\\u4e00-\\u9fa5]+$");
    }

    // 添加新场景对话框方法
    private void showNewSceneDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_new_scene, null);
        EditText majorSceneInput = dialogView.findViewById(R.id.edit_major_scene);
        EditText minorSceneInput = dialogView.findViewById(R.id.edit_minor_scene);

        new MaterialAlertDialogBuilder(requireContext())
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    String majorScene = majorSceneInput.getText().toString().trim();
                    String minorScene = minorSceneInput.getText().toString().trim();

                    // 检查输入是否有效
                    boolean majorValid = isValidSceneName(majorScene);
                    boolean minorValid = isValidSceneName(minorScene);

                    if (!majorValid || !minorValid) {
                        Toast.makeText(requireContext(), "场景中有非法字符", Toast.LENGTH_SHORT).show();
                        if (!majorValid) {
                            majorSceneInput.setText("");
                        }
                        if (!minorValid) {
                            minorSceneInput.setText("");
                        }
                        return;
                    }

                    // 构建新场景
                    String newScene = majorScene + "-" + minorScene;

                    // 将新场景添加到集合的开头
                    Set<String> newScenes = new LinkedHashSet<>();
                    newScenes.add(newScene);  // 新场景放在最前面

                    // 按大场景分组添加其他场景
                    Map<String, List<String>> sceneGroups = new LinkedHashMap<>();
                    for (String scene : scenes) {
                        String[] parts = scene.split("-");
                        if (parts.length == 2) {
                            String major = parts[0];
                            sceneGroups.computeIfAbsent(major, k -> new ArrayList<>()).add(scene);
                        }
                    }

                    // 按顺序添加其他场景
                    for (List<String> group : sceneGroups.values()) {
                        newScenes.addAll(group);
                    }

                    // 更新场景集合
                    scenes = newScenes;
                    updateSceneDisplay();
                    saveData();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    // 修改编辑对话框方法
    private void showEditTodoBoxDialog(TodoBox todoBox) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_todobox, null);
        EditText nameInput = dialogView.findViewById(R.id.edit_todobox_name);
        EditText descriptionInput = dialogView.findViewById(R.id.edit_todobox_description);
        ChipGroup selectedScenesGroup = dialogView.findViewById(R.id.chip_group_selected_scenes);
        ChipGroup locationChipGroup = dialogView.findViewById(R.id.chip_group_locations);
        RecyclerView timeLabelList = dialogView.findViewById(R.id.list_time_labels);
        Button addTimeSpanButton = dialogView.findViewById(R.id.btn_add_time_span);
        
        // 设置现有数据
        nameInput.setText(todoBox.getName());
        if (todoBox.getDescription() != null) {
            descriptionInput.setText(todoBox.getDescription());
        }

        // 设置任务列表
        RecyclerView taskList = dialogView.findViewById(R.id.list_tasks);
        taskList.setLayoutManager(new LinearLayoutManager(getContext()));
        List<Task> availableTasks = getAvailableTasks();
        // 添加当前任务盒中的任务
        if (todoBox.getListData() != null && todoBox.getListData().getList() != null) {
            for (TodoBox.TaskRef ref : todoBox.getListData().getList()) {
                Task task = taskMap.get(ref.getTaskId());
                if (task != null && !availableTasks.contains(task)) {
                    availableTasks.add(task);
                }
            }
        }
        TaskSelectionAdapter taskAdapter = new TaskSelectionAdapter(availableTasks);
        taskList.setAdapter(taskAdapter);

        // 预选当前任务盒中的任务
        if (todoBox.getListData() != null && todoBox.getListData().getList() != null) {
            for (TodoBox.TaskRef ref : todoBox.getListData().getList()) {
                taskAdapter.setTaskSelected(ref.getTaskId(), true);
            }
        }

        // 设置时间标签
        List<Task.TimeLabel> timeLabels = new ArrayList<>(todoBox.getTimeLabels());
        final TimeLabelAdapter timeLabelAdapter = new TimeLabelAdapter(timeLabels, null);  // 先创建适配器

        // 然后设置监听器
        timeLabelAdapter.setActionListener(new TimeLabelAdapter.OnTimeLabelActionListener() {
            @Override
            public void onLabelClick(Task.TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }

            @Override
            public void onDelete(Task.TimeLabel timeLabel, int position) {
                timeLabels.remove(position);
                timeLabelAdapter.notifyItemRemoved(position);
            }

            @Override
            public void onEdit(Task.TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }
        });

        // 设置RecyclerView
        timeLabelList.setLayoutManager(new LinearLayoutManager(getContext()));
        timeLabelList.setAdapter(timeLabelAdapter);

        // 设置添加时间段按钮
        addTimeSpanButton.setOnClickListener(v -> 
            showTimeSpanDialog(timeLabels, timeLabelAdapter));

        // 设置心情状态
        Chip angryChip = dialogView.findViewById(R.id.chip_mood_angry);
        Chip excitedChip = dialogView.findViewById(R.id.chip_mood_excited);
        Chip calmChip = dialogView.findViewById(R.id.chip_mood_calm);
        Chip tiredMoodChip = dialogView.findViewById(R.id.chip_mood_tired);
        Chip depressedChip = dialogView.findViewById(R.id.chip_mood_depressed);
        Chip confusedChip = dialogView.findViewById(R.id.chip_mood_confused);

        if (todoBox.getMoods() != null) {
            angryChip.setChecked(todoBox.getMoods().contains("愤怒"));
            excitedChip.setChecked(todoBox.getMoods().contains("兴奋"));
            calmChip.setChecked(todoBox.getMoods().contains("平定"));
            tiredMoodChip.setChecked(todoBox.getMoods().contains("倦怠"));
            depressedChip.setChecked(todoBox.getMoods().contains("忧郁"));
            confusedChip.setChecked(todoBox.getMoods().contains("迷茫"));
        }

        // 设置健康状态
        Chip healthyChip = dialogView.findViewById(R.id.chip_health_healthy);
        Chip tiredHealthChip = dialogView.findViewById(R.id.chip_health_tired);
        Chip susceptibleChip = dialogView.findViewById(R.id.chip_health_susceptible);
        Chip mildChip = dialogView.findViewById(R.id.chip_health_mild);
        Chip severeChip = dialogView.findViewById(R.id.chip_health_severe);

        if (todoBox.getHealthStates() != null) {
            healthyChip.setChecked(todoBox.getHealthStates().contains("健康"));
            tiredHealthChip.setChecked(todoBox.getHealthStates().contains("疲惫"));
            susceptibleChip.setChecked(todoBox.getHealthStates().contains("易感"));
            mildChip.setChecked(todoBox.getHealthStates().contains("轻症"));
            severeChip.setChecked(todoBox.getHealthStates().contains("重症"));
        }

        // 设置网络类型
        Chip wifiChip = dialogView.findViewById(R.id.chip_wifi);
        Chip mobileChip = dialogView.findViewById(R.id.chip_mobile);
        Chip noNetworkChip = dialogView.findViewById(R.id.chip_no_network);

        if (todoBox.getNetworkTypes() != null) {
            wifiChip.setChecked(todoBox.getNetworkTypes().contains("WiFi"));
            mobileChip.setChecked(todoBox.getNetworkTypes().contains("移动数据"));
            noNetworkChip.setChecked(todoBox.getNetworkTypes().contains("无网络"));
        }

        // 设置地点类型
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setupLocationTypes(locationChipGroup, todoBox);
        }

        new MaterialAlertDialogBuilder(requireContext())
                .setTitle("编辑任务盒")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    String name = nameInput.getText().toString().trim();
                    String description = descriptionInput.getText().toString().trim();

                    if (name.isEmpty()) {
                        Toast.makeText(getContext(), "请输入任务盒名称", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 更新任务盒数据
                    todoBox.setName(name);
                    todoBox.setDescription(description);
                    todoBox.setTimeLabels(new ArrayList<>(timeLabels));

                    // 收集地点类型
                    List<String> selectedLocationTypes = new ArrayList<>();
                    for (int i = 0; i < locationChipGroup.getChildCount(); i++) {
                        View child = locationChipGroup.getChildAt(i);
                        if (child instanceof Chip) {
                            Chip chip = (Chip) child;
                            if (chip.isChecked()) {
                                selectedLocationTypes.add(chip.getText().toString());
                            }
                        }
                    }
                    todoBox.setLocationTypes(selectedLocationTypes);

                    // 收集心情状态
                    List<String> moods = new ArrayList<>();
                    if (angryChip.isChecked()) moods.add("愤怒");
                    if (excitedChip.isChecked()) moods.add("兴奋");
                    if (calmChip.isChecked()) moods.add("平定");
                    if (tiredMoodChip.isChecked()) moods.add("倦怠");
                    if (depressedChip.isChecked()) moods.add("忧郁");
                    if (confusedChip.isChecked()) moods.add("迷茫");
                    todoBox.setMoods(moods);

                    // 收集健康状态
                    List<String> healthStates = new ArrayList<>();
                    if (healthyChip.isChecked()) healthStates.add("健康");
                    if (tiredHealthChip.isChecked()) healthStates.add("疲惫");
                    if (susceptibleChip.isChecked()) healthStates.add("易感");
                    if (mildChip.isChecked()) healthStates.add("轻症");
                    if (severeChip.isChecked()) healthStates.add("重症");
                    todoBox.setHealthStates(healthStates);

                    // 收集网络类型
                    List<String> networkTypes = new ArrayList<>();
                    if (wifiChip.isChecked()) networkTypes.add("WiFi");
                    if (mobileChip.isChecked()) networkTypes.add("移动数据");
                    if (noNetworkChip.isChecked()) networkTypes.add("无网络");
                    todoBox.setNetworkTypes(networkTypes);

                    // 收集选中的任务
                    List<TodoBox.TaskRef> selectedTasks = taskAdapter.getSelectedTasks().stream()
                            .map(task -> {
                                TodoBox.TaskRef ref = new TodoBox.TaskRef();
                                ref.setTaskId(task.getId());
                                ref.setName(task.getName());
                                ref.setDeadline(task.getDeadline());
                                return ref;
                            })
                            .collect(Collectors.toList());

                    // 更新任务盒的任务列表
                    TodoBox.ListData listData = new TodoBox.ListData();
                    listData.setList(selectedTasks);
                    todoBox.setListData(listData);

                    // 保存数据
                    saveData();
                    
                    // 更新界面
                    filterTodoBoxesByScene();
                    adapter.notifyDataSetChanged();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    // 辅助方法：设置心情和健康状况
    private void setupMoodAndHealthChips(View dialogView, TodoBox todoBox) {
        // 获取心情Chips
        Chip angryChip = dialogView.findViewById(R.id.chip_mood_angry);
        Chip excitedChip = dialogView.findViewById(R.id.chip_mood_excited);
        Chip calmChip = dialogView.findViewById(R.id.chip_mood_calm);
        Chip tiredMoodChip = dialogView.findViewById(R.id.chip_mood_tired);
        Chip depressedChip = dialogView.findViewById(R.id.chip_mood_depressed);
        Chip confusedChip = dialogView.findViewById(R.id.chip_mood_confused);

        // 获取健康状况Chips
        Chip healthyChip = dialogView.findViewById(R.id.chip_health_healthy);
        Chip tiredHealthChip = dialogView.findViewById(R.id.chip_health_tired);
        Chip susceptibleChip = dialogView.findViewById(R.id.chip_health_susceptible);
        Chip mildChip = dialogView.findViewById(R.id.chip_health_mild);
        Chip severeChip = dialogView.findViewById(R.id.chip_health_severe);

        // 设置现有心情状态
        List<String> moods = todoBox.getMoods();
        if (moods != null) {
            angryChip.setChecked(moods.contains("愤怒"));
            excitedChip.setChecked(moods.contains("兴奋"));
            calmChip.setChecked(moods.contains("平定"));
            tiredMoodChip.setChecked(moods.contains("倦怠"));
            depressedChip.setChecked(moods.contains("忧郁"));
            confusedChip.setChecked(moods.contains("迷茫"));
        }

        // 设置现有健康状态
        List<String> healthStates = todoBox.getHealthStates();
        if (healthStates != null) {
            healthyChip.setChecked(healthStates.contains("健康"));
            tiredHealthChip.setChecked(healthStates.contains("疲惫"));
            susceptibleChip.setChecked(healthStates.contains("易感"));
            mildChip.setChecked(healthStates.contains("轻症"));
            severeChip.setChecked(healthStates.contains("重症"));
        }
    }

    // 辅助方法：设置地点类型
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setupLocationTypes(ChipGroup locationChipGroup, @Nullable TodoBox todoBox) {
        List<String> locationTypes = new ArrayList<>();
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File stateFile = new File(dataDir, "state.json");
            if (stateFile.exists()) {
                String json = new String(Files.readAllBytes(stateFile.toPath()));
                Map<String, Object> stateData = gson.fromJson(json, 
                    new TypeToken<Map<String, Object>>() {}.getType());
                List<String> types = (List<String>) stateData.get("locationTypes");
                if (types != null) {
                    locationTypes.addAll(types);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "读取状态数据失败", Toast.LENGTH_SHORT).show();
        }

        // 动态创建地点类型勾选框
        locationChipGroup.removeAllViews();  // 先清空现有的视图
        for (String locationType : locationTypes) {
            Chip chip = new Chip(requireContext());
            chip.setText(locationType);
            chip.setCheckable(true);
            
            // 如果是编辑模式，设置已选中的地点类型
            if (todoBox != null && todoBox.getLocationTypes() != null) {
                chip.setChecked(todoBox.getLocationTypes().contains(locationType));
            }
            
            locationChipGroup.addView(chip);
        }
    }

    private List<Task> getAvailableTasks() {
        List<Task> availableTasks = new ArrayList<>();
        long currentTime = System.currentTimeMillis();
        
        // 收集所有已在任务盒中的任务ID
        Set<String> usedTaskIds = new HashSet<>();
        for (TodoBox todoBox : todoBoxes) {
            if (todoBox.getListData() != null && todoBox.getListData().getList() != null) {
                for (TodoBox.TaskRef taskRef : todoBox.getListData().getList()) {
                    usedTaskIds.add(taskRef.getTaskId());
                }
            }
        }

        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");

            if (todoboxFile.exists()) {
                String json = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    json = new String(Files.readAllBytes(todoboxFile.toPath()));
                }
                TodoBoxData todoBoxData = gson.fromJson(json, TodoBoxData.class);
                if (todoBoxData != null && todoBoxData.getTasks() != null) {
                    for (Task task : todoBoxData.getTasks()) {
                        // 基础条件：未完成且（未过期或永久）
                        boolean baseCondition = !task.isCompleted() && 
                                             (task.getDeadline() == 0 || task.getDeadline() > currentTime);
                        
                        // 额外条件：未在任何任务盒中 或 被收藏
                        boolean extraCondition = !usedTaskIds.contains(task.getId()) || task.isFavorite();
                        
                        if (baseCondition && extraCondition) {
                            availableTasks.add(task);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), 
                "加载任务失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
        return availableTasks;
    }

    // 添加场景芯片的辅助方法
    private void addSceneChip(String scene, ChipGroup chipGroup, Set<String> selectedScenes) {
        // 检查是否已存在相同场景的芯片
        for (int i = 0; i < chipGroup.getChildCount(); i++) {
            Chip chip = (Chip) chipGroup.getChildAt(i);
            if (chip.getText().toString().equals(scene)) {
                return; // 已存在则直接返回
            }
        }

        Chip chip = new Chip(requireContext());
        chip.setText(scene);
        chip.setCloseIconVisible(true);
        chip.setOnCloseIconClickListener(v -> {
            chipGroup.removeView(chip);
            selectedScenes.remove(scene);
        });
        chipGroup.addView(chip);
    }

    // 移除场景芯片的辅助方法
    private void removeSceneChip(String scene, ChipGroup chipGroup) {
        for (int i = 0; i < chipGroup.getChildCount(); i++) {
            Chip chip = (Chip) chipGroup.getChildAt(i);
            if (chip.getText().toString().equals(scene)) {
                chipGroup.removeView(chip);
                break;
            }
        }
    }

    // 编辑任务的对话框
    private void showEditTaskDialog(Task task) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_task, null);
        EditText nameInput = dialogView.findViewById(R.id.edit_task_name);
        EditText descriptionInput = dialogView.findViewById(R.id.edit_task_description);
        Button deadlineButton = dialogView.findViewById(R.id.btn_set_deadline);
        RecyclerView timeLabelsRecyclerView = dialogView.findViewById(R.id.recycler_time_labels);
        Button addTimeSpanButton = dialogView.findViewById(R.id.btn_add_time_span);
        CheckBox foreverCheckbox = dialogView.findViewById(R.id.checkbox_forever);
        CheckBox hometownCheckbox = dialogView.findViewById(R.id.checkbox_hometown);
        CheckBox residenceCheckbox = dialogView.findViewById(R.id.checkbox_residence);

        // 填充现有数据
        nameInput.setText(task.getName());
        descriptionInput.setText(task.getDescription());
        deadlineButton.setText(formatDate(task.getDeadline()));
        foreverCheckbox.setChecked(task.getDeadline() == 0);
        hometownCheckbox.setChecked(task.isHometown());
        residenceCheckbox.setChecked(task.isResidence());

        // 设置截止日期选择
        Calendar calendar = Calendar.getInstance();
        long[] deadline = {task.getDeadline()};

        deadlineButton.setOnClickListener(v -> {
            if (!foreverCheckbox.isChecked()) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(
                    requireContext(),
                    (view, year, month, dayOfMonth) -> {
                        calendar.set(year, month, dayOfMonth);
                        deadline[0] = calendar.getTimeInMillis();
                        deadlineButton.setText(formatDate(deadline[0]));
                    },
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH)
                );
                datePickerDialog.show();
            }
        });

        // 设置永久选项
        foreverCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                deadline[0] = 0;
                deadlineButton.setText(formatDate(0));
                deadlineButton.setEnabled(false);
            } else {
                deadlineButton.setEnabled(true);
            }
        });

        // 创建时间标签列表和适配器
        List<Task.TimeLabel> timeLabels = new ArrayList<>(task.getTimeLabels());
        TimeLabelAdapter timeLabelAdapter = new TimeLabelAdapter(timeLabels, null);

        // 创建监听器
        TimeLabelAdapter.OnTimeLabelActionListener listener = new TimeLabelAdapter.OnTimeLabelActionListener() {
            @Override
            public void onLabelClick(Task.TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }

            @Override
            public void onDelete(Task.TimeLabel timeLabel, int position) {
                timeLabels.remove(position);
                timeLabelAdapter.notifyItemRemoved(position);
            }

            @Override
            public void onEdit(Task.TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }
        };

        // 设置监听器
        timeLabelAdapter.setActionListener(listener);

        // 设置RecyclerView
        timeLabelsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        timeLabelsRecyclerView.setAdapter(timeLabelAdapter);

        // 设置添加时间段按钮
        addTimeSpanButton.setOnClickListener(v -> 
            showTimeSpanDialog(timeLabels, timeLabelAdapter));

        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("编辑任务")
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                String name = nameInput.getText().toString().trim();
                if (name.isEmpty()) {
                    Toast.makeText(getContext(), "请输入任务名称", Toast.LENGTH_SHORT).show();
                    return;
                }

                task.setName(name);
                task.setDescription(descriptionInput.getText().toString().trim());
                task.setDeadline(deadline[0]);
                task.setTimeLabels(new ArrayList<>(timeLabels));
                task.setHometown(hometownCheckbox.isChecked());
                task.setResidence(residenceCheckbox.isChecked());

                // 保存修改后的任务
                saveTaskData(task);
                adapter.notifyDataSetChanged();
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void showTimeSpanDialog(List<Task.TimeLabel> timeLabels, TimeLabelAdapter adapter) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_timespan, null);
        
        // 获取视图引用
        ClockTimeSelector clockTimeSelector = dialogView.findViewById(R.id.clock_time_selector);
        TextView selectedTimeText = dialogView.findViewById(R.id.text_selected_time);
        ChipGroup dayTypeGroup = dialogView.findViewById(R.id.chip_group_day_types);
        Chip workdayChip = dialogView.findViewById(R.id.chip_workday);
        Chip companionChip = dialogView.findViewById(R.id.chip_companion);
        Chip freedayChip = dialogView.findViewById(R.id.chip_freeday);

        // 设置时钟选择器的监听器
        clockTimeSelector.setOnTimeChangedListener((startHour, startMinute, endHour, endMinute) -> {
            selectedTimeText.setText(String.format(Locale.getDefault(), 
                "%02d:%02d-%02d:%02d", startHour, startMinute, endHour, endMinute));
        });

        // 显示对话框
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("添加时间段")
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                // 获取选中的日期类型
                String dayType = null;
                if (workdayChip.isChecked()) {
                    dayType = "工作日";
                } else if (companionChip.isChecked()) {
                    dayType = "陪伴日";
                } else if (freedayChip.isChecked()) {
                    dayType = "自由日";
                }

                if (dayType == null) {
                    Toast.makeText(getContext(), "请选择日期类型", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 创建新的时间标签
                Task.TimeLabel timeLabel = new Task.TimeLabel();
                timeLabel.setDayType(dayType);
                timeLabel.setStartHour(clockTimeSelector.getStartHour());
                timeLabel.setStartMinute(clockTimeSelector.getStartMinute());
                timeLabel.setEndHour(clockTimeSelector.getEndHour());
                timeLabel.setEndMinute(clockTimeSelector.getEndMinute());

                // 添加到列表并更新界面
                timeLabels.add(timeLabel);
                adapter.notifyDataSetChanged();
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void showEditTimeLabelDialog(Task.TimeLabel timeLabel, List<Task.TimeLabel> timeLabels, TimeLabelAdapter adapter) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_timespan, null);
        
        // 获取视图引用
        ClockTimeSelector clockTimeSelector = dialogView.findViewById(R.id.clock_time_selector);
        TextView selectedTimeText = dialogView.findViewById(R.id.text_selected_time);
        ChipGroup dayTypeGroup = dialogView.findViewById(R.id.chip_group_day_types);
        Chip workdayChip = dialogView.findViewById(R.id.chip_workday);
        Chip companionChip = dialogView.findViewById(R.id.chip_companion);
        Chip freedayChip = dialogView.findViewById(R.id.chip_freeday);

        // 设置现有值
        clockTimeSelector.setTime(
            timeLabel.getStartHour(),
            timeLabel.getStartMinute(),
            timeLabel.getEndHour(),
            timeLabel.getEndMinute()
        );

        switch (timeLabel.getDayType()) {
            case "工作日":
                workdayChip.setChecked(true);
                break;
            case "陪伴日":
                companionChip.setChecked(true);
                break;
            case "自由日":
                freedayChip.setChecked(true);
                break;
        }

        // 设置时钟选择器的监听器
        clockTimeSelector.setOnTimeChangedListener((startHour, startMinute, endHour, endMinute) -> {
            selectedTimeText.setText(String.format(Locale.getDefault(), 
                "%02d:%02d-%02d:%02d", startHour, startMinute, endHour, endMinute));
        });

        // 显示对话框
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("编辑时间段")
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                // 获取选中的日期类型
                String dayType = null;
                if (workdayChip.isChecked()) {
                    dayType = "工作日";
                } else if (companionChip.isChecked()) {
                    dayType = "陪伴日";
                } else if (freedayChip.isChecked()) {
                    dayType = "自由日";
                }

                if (dayType == null) {
                    Toast.makeText(getContext(), "请选择日期类型", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 更新时间值
                timeLabel.setDayType(dayType);
                timeLabel.setStartHour(clockTimeSelector.getStartHour());
                timeLabel.setStartMinute(clockTimeSelector.getStartMinute());
                timeLabel.setEndHour(clockTimeSelector.getEndHour());
                timeLabel.setEndMinute(clockTimeSelector.getEndMinute());

                adapter.notifyDataSetChanged();
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void saveTaskData(Task task) {
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");

            if (todoboxFile.exists()) {
                String json = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    json = new String(Files.readAllBytes(todoboxFile.toPath()));
                }
                TodoBoxData todoBoxData = gson.fromJson(json, TodoBoxData.class);
                if (todoBoxData != null) {
                    List<Task> allTasks = todoBoxData.getTasks();
                    
                    // 找到要更新的任务
                    for (int i = 0; i < allTasks.size(); i++) {
                        Task currentTask = allTasks.get(i);
                        if (currentTask.getId().equals(task.getId())) {
                            allTasks.set(i, task);
                            todoBoxData.setTasks(allTasks);
                            
                            // 保存回文件
                            try (FileWriter writer = new FileWriter(todoboxFile)) {
                                gson.toJson(todoBoxData, writer);
                            }
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), 
                "保存任务失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void showAddTodoBoxDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_todobox, null);
        EditText nameInput = dialogView.findViewById(R.id.edit_todobox_name);
        EditText descriptionInput = dialogView.findViewById(R.id.edit_todobox_description);
        ChipGroup selectedScenesGroup = dialogView.findViewById(R.id.chip_group_selected_scenes);
        ChipGroup locationChipGroup = dialogView.findViewById(R.id.chip_group_locations);
        RecyclerView timeLabelList = dialogView.findViewById(R.id.list_time_labels);
        Button addTimeSpanButton = dialogView.findViewById(R.id.btn_add_time_span);
        
        // 创建一个新的场景集合用于对话框
        Set<String> dialogSelectedScenes = new HashSet<>();
        
        // 设置场景选择适配器
        RecyclerView scenesRecyclerView = dialogView.findViewById(R.id.recycler_scenes);
        scenesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        SceneSelectionAdapter sceneAdapter = new SceneSelectionAdapter(
            dialogSelectedScenes,
            (scene, selected) -> {
                if (selected) {
                    dialogSelectedScenes.add(scene);
                    addSceneChip(scene, selectedScenesGroup, dialogSelectedScenes);
                } else {
                    dialogSelectedScenes.remove(scene);
                    removeSceneChip(scene, selectedScenesGroup);
                }
            }
        );
        scenesRecyclerView.setAdapter(sceneAdapter);
        
        // 设置场景数据
        if (scenes != null) {
            sceneAdapter.setScenes(new ArrayList<>(scenes));
        }

        // 设置任务列表
        RecyclerView taskList = dialogView.findViewById(R.id.list_tasks);
        taskList.setLayoutManager(new LinearLayoutManager(getContext()));
        List<Task> availableTasks = getAvailableTasks();
        TaskSelectionAdapter taskAdapter = new TaskSelectionAdapter(availableTasks);
        taskList.setAdapter(taskAdapter);

        // 获取心情和健康状况的Chip
        Chip angryChip = dialogView.findViewById(R.id.chip_mood_angry);
        Chip excitedChip = dialogView.findViewById(R.id.chip_mood_excited);
        Chip calmChip = dialogView.findViewById(R.id.chip_mood_calm);
        Chip tiredMoodChip = dialogView.findViewById(R.id.chip_mood_tired);
        Chip depressedChip = dialogView.findViewById(R.id.chip_mood_depressed);
        Chip confusedChip = dialogView.findViewById(R.id.chip_mood_confused);

        Chip healthyChip = dialogView.findViewById(R.id.chip_health_healthy);
        Chip tiredHealthChip = dialogView.findViewById(R.id.chip_health_tired);
        Chip susceptibleChip = dialogView.findViewById(R.id.chip_health_susceptible);
        Chip mildChip = dialogView.findViewById(R.id.chip_health_mild);
        Chip severeChip = dialogView.findViewById(R.id.chip_health_severe);

        // 创建时间标签列表和适配器
        List<Task.TimeLabel> timeLabels = new ArrayList<>();
        TimeLabelAdapter timeLabelAdapter = new TimeLabelAdapter(timeLabels, null);

        // 创建监听器
        TimeLabelAdapter.OnTimeLabelActionListener listener = new TimeLabelAdapter.OnTimeLabelActionListener() {
            @Override
            public void onLabelClick(Task.TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }

            @Override
            public void onDelete(Task.TimeLabel timeLabel, int position) {
                timeLabels.remove(position);
                timeLabelAdapter.notifyItemRemoved(position);
            }

            @Override
            public void onEdit(Task.TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }
        };

        // 设置监听器
        timeLabelAdapter.setActionListener(listener);

        // 设置RecyclerView
        timeLabelList.setLayoutManager(new LinearLayoutManager(getContext()));
        timeLabelList.setAdapter(timeLabelAdapter);

        // 设置添加时间段按钮
        addTimeSpanButton.setOnClickListener(v -> 
            showTimeSpanDialog(timeLabels, timeLabelAdapter));

        // 初始化场景选择
        initializeSceneSelection(scenesRecyclerView, selectedScenesGroup, dialogSelectedScenes);

        // 读取并设置地点类型
        setupLocationTypes(locationChipGroup, null);

        new MaterialAlertDialogBuilder(requireContext())
                .setTitle("添加任务盒")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    String name = nameInput.getText().toString().trim();
                    String description = descriptionInput.getText().toString().trim();

                    if (name.isEmpty()) {
                        Toast.makeText(getContext(), "请输入任务盒名称", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 创建新的任务盒
                    TodoBox todoBox = new TodoBox();
                    todoBox.setId(UUID.randomUUID().toString());
                    todoBox.setName(name);
                    todoBox.setDescription(description);
                    todoBox.setScenes(new HashSet<>(dialogSelectedScenes));
                    todoBox.setTimeLabels(new ArrayList<>(timeLabels));

                    // 收集心情状态
                    List<String> moods = new ArrayList<>();
                    if (angryChip.isChecked()) moods.add("愤怒");
                    if (excitedChip.isChecked()) moods.add("兴奋");
                    if (calmChip.isChecked()) moods.add("平定");
                    if (tiredMoodChip.isChecked()) moods.add("倦怠");
                    if (depressedChip.isChecked()) moods.add("忧郁");
                    if (confusedChip.isChecked()) moods.add("迷茫");
                    todoBox.setMoods(moods);

                    // 收集健康状态
                    List<String> healthStates = new ArrayList<>();
                    if (healthyChip.isChecked()) healthStates.add("健康");
                    if (tiredHealthChip.isChecked()) healthStates.add("疲惫");
                    if (susceptibleChip.isChecked()) healthStates.add("易感");
                    if (mildChip.isChecked()) healthStates.add("轻症");
                    if (severeChip.isChecked()) healthStates.add("重症");
                    todoBox.setHealthStates(healthStates);

                    // 收集地点类型
                    List<String> selectedLocationTypes = new ArrayList<>();
                    for (int i = 0; i < locationChipGroup.getChildCount(); i++) {
                        View child = locationChipGroup.getChildAt(i);
                        if (child instanceof Chip) {
                            Chip chip = (Chip) child;
                            if (chip.isChecked()) {
                                selectedLocationTypes.add(chip.getText().toString());
                            }
                        }
                    }
                    todoBox.setLocationTypes(selectedLocationTypes);

                    // 收集选中的任务
                    List<TodoBox.TaskRef> selectedTasks = taskAdapter.getSelectedTasks().stream()
                            .map(task -> {
                                TodoBox.TaskRef ref = new TodoBox.TaskRef();
                                ref.setTaskId(task.getId());
                                ref.setName(task.getName());
                                ref.setDeadline(task.getDeadline());
                                return ref;
                            })
                            .collect(Collectors.toList());

                    // 更新任务盒的任务列表
                    TodoBox.ListData listData = new TodoBox.ListData();
                    listData.setList(selectedTasks);
                    todoBox.setListData(listData);

                    // 更新全局场景集合
                    scenes.addAll(dialogSelectedScenes);

                    // 保存数据并更新界面
                    todoBoxes.add(todoBox);

                    // 保存数据
                    saveData();
                    
                    // 更新界面
                    filterTodoBoxesByScene();
                    adapter.notifyDataSetChanged();
                    
                    Toast.makeText(getContext(), "任务盒已添加", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    // 初始化场景选择
    private void initializeSceneSelection(RecyclerView majorScenesList,
                                          ChipGroup selectedScenesGroup,
                                          Set<String> selectedScenes) {
        if (majorScenesList == null || selectedScenesGroup == null || selectedScenes == null) {
            return;
        }

        majorScenesList.setLayoutManager(new LinearLayoutManager(requireContext()));
        SceneSelectionAdapter sceneAdapter = new SceneSelectionAdapter(selectedScenes,
                (scene, selected) -> {
                    if (selected) {
                        selectedScenes.add(scene);
                        addSelectedSceneChip(selectedScenesGroup, scene, selectedScenes);
                    } else {
                        selectedScenes.remove(scene);
                        removeSelectedSceneChip(selectedScenesGroup, scene);
                    }
                });
        majorScenesList.setAdapter(sceneAdapter);
        sceneAdapter.setScenes(new ArrayList<>(scenes));

        // 显示已选场景
        for (String scene : selectedScenes) {
            addSelectedSceneChip(selectedScenesGroup, scene, selectedScenes);
        }
    }

    // 添加选中场景的Chip
    private void addSelectedSceneChip(ChipGroup chipGroup, String scene, Set<String> selectedScenes) {
        // 检查是否已存在
        for (int i = 0; i < chipGroup.getChildCount(); i++) {
            Chip chip = (Chip) chipGroup.getChildAt(i);
            if (chip.getText().toString().equals(scene)) {
                return;
            }
        }

        Chip chip = new Chip(requireContext());
        chip.setText(scene);
        chip.setCloseIconVisible(true);
        chip.setOnCloseIconClickListener(v -> {
            chipGroup.removeView(chip);
            selectedScenes.remove(scene);
        });
        chipGroup.addView(chip);
    }

    // 移除选中场景的Chip
    private void removeSelectedSceneChip(ChipGroup chipGroup, String scene) {
        for (int i = 0; i < chipGroup.getChildCount(); i++) {
            Chip chip = (Chip) chipGroup.getChildAt(i);
            if (chip.getText().toString().equals(scene)) {
                chipGroup.removeView(chip);
                break;
            }
        }
    }

    // 添加日期格式化方法
    private String formatDate(long timestamp) {
        if (timestamp == 0) {
            return "无截止日期";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        return sdf.format(new Date(timestamp));
    }


    // 添加检查任务时间段的辅助方法
    private boolean isTaskTimeValid(Task task) {
        if (task.getTimeLabels() == null || task.getTimeLabels().isEmpty()) {
            return true;  // 没有时间标签的任务始终有效
        }

        Calendar now = Calendar.getInstance();
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int minute = now.get(Calendar.MINUTE);
        int dayOfWeek = now.get(Calendar.DAY_OF_WEEK);
        
        // 获取当前星期对应的日期类型
        String currentDay = getDayOfWeek(dayOfWeek);
        String dayType = getDayType(currentDay);
        
        if (dayType == null) {
            return false;  // 如果获取不到日期类型，任务无效
        }
        
        // 当前时间（以分钟为单位）
        int currentTime = hour * 60 + minute;
        
        // 检查每个时间标签
        for (Task.TimeLabel timeLabel : task.getTimeLabels()) {
            if (timeLabel.getDayType().equals(dayType)) {
                if (timeLabel.isAllDay()) {
                    return true;  // 全天任务始终有效
                }
                
                // 获取开始和结束时间
                int startTime = timeLabel.getStartHour() * 60 + timeLabel.getStartMinute();
                int endTime = timeLabel.getEndHour() * 60 + timeLabel.getEndMinute();
                
                // 检查时间是否在范围内
                if (endTime < startTime) {  // 跨天的情况
                    if (currentTime >= startTime || currentTime <= endTime) {
                        return true;
                    }
                } else {  // 不跨天的情况
                    if (currentTime >= startTime && currentTime <= endTime) {
                        return true;
                    }
                }
            }
        }
        
        return false;  // 没有匹配的时间标签
    }

    private void filterTodoBoxes(String query) {
        if (todoBoxes == null) return;

        List<TodoBox> filteredBoxes = new ArrayList<>();
        for (TodoBox todoBox : todoBoxes) {
            String name = todoBox.getName().toLowerCase();
            String description = todoBox.getDescription() != null ? todoBox.getDescription().toLowerCase() : "";
            
            if (name.contains(query) || description.contains(query)) {
                filteredBoxes.add(todoBox);
            }
        }

        // 更新搜索结果列表
        if (searchResultsAdapter != null) {
            searchResultsAdapter.updateTodoBoxes(filteredBoxes);
        }
        
        // 根据是否有搜索结果显示或隐藏搜索结果列表
        RecyclerView searchResultsRecyclerView = binding.searchResultsRecyclerView;
        if (filteredBoxes.isEmpty()) {
            searchResultsRecyclerView.setVisibility(View.GONE);
        } else {
            searchResultsRecyclerView.setVisibility(View.VISIBLE);
        }
    }
}
